import {
    createSlice
} from "@reduxjs/toolkit";
import { useSelector } from "react-redux";
import { getHospitalSet ,getHospitalSetLockId,postHospitalSet,putHospitalSet} from "@/api/hosp";
import {changeLoading,changePageInfo} from "@/store/slice/common";

const hospSlice = createSlice({
    name:"hosp",
    initialState:{
        hospSetList:[]
    },
    reducers :{
        upHospSetList(state,{ payload}){
            state.hospSetList = payload;
        },
        changeStateById(state,{ payload}){
            const info:any = state.hospSetList.find((v:any)=>v.id === payload);
            info.state = info.state === 0?1:0;
        }
    }
    
})

export const {upHospSetList,changeStateById} = hospSlice.actions;
//获取状态列表
export const getHospitalSetAsync = function(page:number,limit:number){
    return async (dispatch:any) =>{
        dispatch(changeLoading(true))
        const result: any = await getHospitalSet(page,limit);
        // console.log(result);
        
        dispatch(upHospSetList(result.data.records));// 更新新闻设置列表状态
        dispatch(changePageInfo({
            current:result.data.current,
            total:result.data.total,
            pageSize:result.data.size
        }))
        dispatch(changeLoading(false));
    }
}

// 完成锁定2:更新服务端的锁定状态，然后重新获取当前页的信息，进行渲染
// 优点：可以将最后操作以后的最新数据进行呈现
export const getHospitalSetLockIdAsync = function(id:number,status: number){
    return async (dispatch:any,getState:any) =>{
        await getHospitalSetLockId(id,status);
        const {current,pageSize} = getState().common.pageInfo
        dispatch(getHospitalSetAsync(current, pageSize));
    }
}
// 完成锁定1： 优点：减少ajax请求
// export const getHospitalSetLockIdAsync = function(id:number,status:number){
//     return async (dispatch:any)=>{
//         await getHospitalSetLockId(id,status);
//         dispatch(changeStateById(id));
//     }
// }

// 添加或修改医院设置
export const postHospitalSetAsync = (body:any)=>{
    return async (dispatch:any,getState: any)=>{
        if(body.id){
            // 修改
            await putHospitalSet(body)
        } else  {
            // 添加
            await postHospitalSet(body);
        }
        const {current,pageSize} = getState().commin.pageInfo;
        dispatch(getHospitalSetAsync(current,pageSize));
    }
}


// 导出状态
export const useSelectorHosp = ()=>useSelector((state: any)=>state.hosp);
export default hospSlice.reducer;